package com.changli04.threadsafemore.singleton;

public class BankTest {
    static Bank b1 = null;
    static Bank b2 = null;
    public static void main(String[] args) {

        Thread t1 = new Thread(){
            @Override
            public void run() {
                b1 = Bank.getInstance();
//                System.out.println(b1);
            }
        };
        Thread t2 = new Thread(){
            @Override
            public void run() {
                 b2 = Bank.getInstance();
//                System.out.println(b2);

            }
        };

        t1.start();
        t2.start();
        try {
            t1.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        try {
            t2.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(b1);
        System.out.println(b2);
        System.out.println(b1 == b2);

    }
}

// 同步方法 一：：

//class Bank {
//    private Bank (){
//
//    }
//    private static Bank  instance = null;
//    public static synchronized Bank getInstance(){
//        if(instance == null){
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//            instance = new Bank();
//        }
//        return instance;
//    }
//}

//同步方法二：：：



//class Bank {
//    private Bank (){
//
//    }
//    private static Bank  instance = null;
//    public static Bank getInstance(){
//        synchronized (Bank.class) {
//            if(instance == null){
//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                }
//                instance = new Bank();
//            }
//            return instance;
//        }
//    }
//}

//同步方法三：：：

class Bank {
    private Bank (){}

    private static Bank  instance = null;

    public static Bank getInstance(){
        if(instance == null){
            synchronized (Bank.class) {
                if(instance == null){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    instance = new Bank();
                }

            }
        }
        return instance;
    }
}
